//
//  BoxTableViewController.m
//  myhuibao
//
//  Created by li jun on 13-3-8.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "BoxTableViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "BoxCell.h"
@interface BoxTableViewController ()

@end

@implementation BoxTableViewController
@synthesize mainTable;
@synthesize delegate;
@synthesize selectedIds;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self getSearchResult];
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [mainTable release];
    [super dealloc];
}
- (void) getSearchResult{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxList];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
    [request setPostValue:[NSString stringWithFormat:@"%@",_diningDate] forKey:@"diningDate"];
    [request setPostValue:[NSString stringWithFormat:@"%d",_diningTime] forKey:@"diningTime"];
    [request setDelegate: self];
    [request startAsynchronous];
    
    
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    NSArray *ss = [selectedIds componentsSeparatedByString:@","];
//    NSLog(@"%@",ss);

    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        bool selected = [self isArray:ss contain:[NSString stringWithFormat:@"%d",[[item valueForKey:@"BOX_ID"] intValue] ]];
        if (selected)
            [item setValue:@"YES" forKey:@"checked"];
        else
            [item setValue:@"NO" forKey:@"checked"];
    }
    

    [mainTable reloadData];
    // Use when fetching binary data
    //    NSData *responseData = [request responseData];
}
- (bool)isArray:(NSArray *)a contain:(NSString*)s
{    
    for(NSString *ss in a)
    {
        if ([s isEqualToString:ss]) {
            return true;
        }
    }
    return false;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}


// 列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 84;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"BoxCellIdentifier";
    
    BoxCell *cell = (BoxCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //        if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"BoxCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    //        }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    
    cell.lbName.text = [item valueForKey:@"BOX_NAME"];
    cell.lbMemo.text = [item valueForKey:@"SEAT_TYPE"];
    cell.checked = [[item valueForKey:@"checked"] boolValue];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    BOOL checked = [[item valueForKey:@"checked"] boolValue];
    BoxCell *cell = (BoxCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (checked) {
        [cell setChecked:false];
        [item setValue:@"NO" forKey:@"checked"];

    }else{
        [cell setChecked:true];
        [item setValue:@"YES" forKey:@"checked"];

    }
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    //其他cell的事件
    
}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)doSave:(id)sender {
    NSString *ids=@"";
    NSString *names=@"";
    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        BOOL checked = [[item valueForKey:@"checked"] boolValue];
        if(checked)
        {
            ids = [ids stringByAppendingFormat:@"%@,",[item valueForKey:@"BOX_ID"]];
            names = [names stringByAppendingFormat:@"%@,",[item valueForKey:@"BOX_NAME"]];
        }
    }
    if([ids isEqualToString:@""]==NO){
        NSLog(@"%@", names);

        [delegate passBoxNames:names withIds:ids];
        [self.navigationController popViewControllerAnimated:YES];

    }
}
@end
